<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="1200px"
    append-to-body
    @close="handleClose"
  >
    <!-- 提示信息 -->
    <el-alert
      v-if="resourceName"
      :title="`正在管理 ${resourceName} 的API Key`"
      type="info"
      :closable="false"
      style="margin-bottom: 15px;"
    />

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增Key</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh-right"
          size="mini"
          @click="handleRecover"
        >恢复限流Key</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- API Key列表 -->
    <el-table
      v-loading="loading"
      :data="keyList"
      @selection-change="handleSelectionChange"
      max-height="400"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="Key名称" align="center" prop="keyName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="API Key" align="center" prop="apiKey" width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ maskApiKey(scope.row.apiKey) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'available'" type="success">可用</el-tag>
          <el-tag v-else-if="scope.row.status === 'in_use'" type="primary">使用中</el-tag>
          <el-tag v-else-if="scope.row.status === 'rate_limited'" type="warning">限流</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80" />
      <el-table-column label="并发数" align="center" width="100">
        <template slot-scope="scope">
          {{ scope.row.currentConcurrency || 0 }}/{{ scope.row.maxConcurrency }}
        </template>
      </el-table-column>
      <el-table-column label="调用统计" align="center" width="120">
        <template slot-scope="scope">
          <span>总计: {{ scope.row.totalCalls || 0 }}</span><br/>
          <span style="color: #67C23A;">成功: {{ scope.row.successCalls || 0 }}</span> /
          <span style="color: #F56C6C;">失败: {{ scope.row.failedCalls || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成功率" align="center" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.totalCalls > 0">
            {{ ((scope.row.successCalls / scope.row.totalCalls) * 100).toFixed(1) }}%
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑Key对话框 -->
    <el-dialog
      :title="formTitle"
      :visible.sync="formOpen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="Key名称" prop="keyName">
          <el-input v-model="form.keyName" placeholder="请输入Key名称，如：生产环境Key-1" />
        </el-form-item>
        <el-form-item label="API Key" prop="apiKey">
          <el-input v-model="form.apiKey" type="textarea" :rows="3" placeholder="请输入API Key" />
        </el-form-item>
        <el-form-item label="API Secret" prop="apiSecret">
          <el-input v-model="form.apiSecret" placeholder="可选，某些服务需要" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" :max="100" />
          <span style="margin-left: 10px; color: #999; font-size: 12px;">数值越大优先级越高</span>
        </el-form-item>
        <el-form-item label="最大并发数" prop="maxConcurrency">
          <el-input-number v-model="form.maxConcurrency" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="available">可用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listApiKeyPool, getApiKeyPool, addApiKeyPool, updateApiKeyPool, delApiKeyPool, recoverRateLimitedKeys } from "@/api/tzai/apiKeyPool";

export default {
  name: "ApiKeyManager",
  props: {
    // 是否显示对话框
    show: {
      type: Boolean,
      default: false
    },
    // 资源类型：ai_model 或 tts_engine
    resourceType: {
      type: String,
      default: ""
    },
    // 资源ID
    resourceId: {
      type: Number,
      default: null
    },
    // 资源名称（用于显示）
    resourceName: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // API Key列表
      keyList: [],
      // 表单对话框
      formOpen: false,
      formTitle: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        keyName: [
          { required: true, message: "Key名称不能为空", trigger: "blur" }
        ],
        apiKey: [
          { required: true, message: "API Key不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit('update:show', val);
      }
    },
    dialogTitle() {
      const typeText = this.resourceType === 'ai_model' ? 'AI模型' : 'TTS引擎';
      return `${typeText} API Key管理`;
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.getList();
      }
    }
  },
  methods: {
    /** 查询API Key列表 */
    getList() {
      // 验证必要参数
      if (!this.resourceType || !this.resourceId || this.resourceId === 0) {
        this.loading = false;
        return;
      }
      
      this.loading = true;
      const queryParams = {
        resourceType: this.resourceType,
        resourceId: this.resourceId
      };
      listApiKeyPool(queryParams).then(response => {
        this.keyList = response.rows || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 遮罩API Key */
    maskApiKey(key) {
      if (!key) return '';
      if (key.length <= 12) return key;
      return key.substring(0, 8) + '****' + key.substring(key.length - 4);
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.keyId);
      this.multiple = !selection.length;
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm();
      this.form.resourceType = this.resourceType;
      this.form.resourceId = this.resourceId;
      this.formOpen = true;
      this.formTitle = "添加API Key";
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm();
      const keyId = row.keyId;
      getApiKeyPool(keyId).then(response => {
        this.form = response.data;
        this.formOpen = true;
        this.formTitle = "修改API Key";
      });
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.keyId != null) {
            updateApiKeyPool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.formOpen = false;
              this.getList();
            });
          } else {
            addApiKeyPool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.formOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const keyIds = row.keyId || this.ids;
      this.$modal.confirm('是否确认删除选中的API Key？').then(function() {
        return delApiKeyPool(keyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /** 恢复限流Key */
    handleRecover() {
      this.$modal.confirm('是否恢复所有限流中的Key？').then(() => {
        return recoverRateLimitedKeys();
      }).then(() => {
        this.$modal.msgSuccess("恢复成功");
        this.getList();
      }).catch(() => {});
    },
    
    /** 表单重置 */
    resetForm() {
      this.form = {
        keyId: null,
        keyName: null,
        resourceType: this.resourceType,
        resourceId: this.resourceId,
        apiKey: null,
        apiSecret: null,
        priority: 10,
        maxConcurrency: 10,
        status: 'available'
      };
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    
    /** 取消表单 */
    cancelForm() {
      this.formOpen = false;
      this.resetForm();
    },
    
    /** 关闭对话框 */
    handleClose() {
      this.$emit('update:show', false);
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>

